#!/usr/bin/env python
# -*- coding: utf8 -*-
import os
import sys
import re
import cymysql
from urlparse import urlparse


def get_project_root(dirname):
    filepath = os.path.abspath(__file__)
    if os.path.islink(filepath):
        filepath = os.readlink(filepath)
    index = filepath.rindex(dirname)
    root = filepath[:index + len(dirname)]
    return root

BASE_DIR = get_project_root('labor')
sys.path.insert(0, BASE_DIR)
os.chdir(BASE_DIR)

from utils.getconf import config_getter
dbcfg = config_getter.get('mysql.region_ro')

conn = cymysql.connect(host=dbcfg.host, port=dbcfg.port, user=dbcfg.user, passwd=dbcfg.passwd, db=dbcfg.db, charset=dbcfg.charset)
conn.autocommit(True)


def query(sql):
    cur = conn.cursor(cymysql.cursors.DictCursor)
    try:
        cur.execute(sql)
        queryset = cur.fetchall()
        return queryset
    except Exception, e:
        raise e
    finally:
        cur.close()


def parse_input(arg):
    if re.match(r'^[a-z0-9]+$', arg):
        return {"service_id": arg}

    m = re.match(r'(?P<tenant_name>[\w\-]+)\.(?P<service_alias>[\w\-]+)', arg)
    if m:
        data = m.groupdict().copy()
        return data

    parsed_url = urlparse(arg)
    path = parsed_url.path
    m = re.match(r'^/(:?apps|ajax)/(?P<tenant_name>[\w\-]+)/(?P<service_alias>[\w\-]+)', path)
    if m:
        data = m.groupdict().copy()
        return data

    raise ValueError("unsupport argument %s" % arg)


def get_basic_info(*args, **kwargs):
    if 'service_id' in kwargs:
        sql1 = """select tenant_id, service_alias from tenant_services where service_id='{}'""".format(kwargs['service_id'])
        qs1 = query(sql1)
        tenant_id = qs1[0]['tenant_id']
        sql2 = """select name from tenants where uuid='{}'""".format(tenant_id)
        qs2 = query(sql2)
        tenant_name = qs2[0]['name']
        service_alias = qs1[0]['service_alias']
        return tenant_name, service_alias, tenant_id, kwargs['service_id']
    else:
        sql1 = """select uuid from tenants where name='{}'""".format(kwargs['tenant_name'])
        qs1 = query(sql1)
        tenant_id = qs1[0]['uuid']
        sql2 = """select service_id from tenant_services where tenant_id='{}' and service_alias='{}'""".format(tenant_id, kwargs['service_alias'])
        qs2 = query(sql2)
        service_id = qs2[0]['service_id']
        return kwargs['tenant_name'], kwargs['service_alias'], tenant_id, service_id


def main():
    if len(sys.argv) == 1:
        arg = raw_input("type a url or service_id or <tenant_name>.<service_alias>: \n")
    else:
        arg = sys.argv[1]
    data = parse_input(arg)
    tenant_name, service_alias, tenant_id, service_id = get_basic_info(**data)
    print "query service is: {}.{}".format(tenant_name, service_alias)
    print "persistence storage path: /grdata/tenant/{}/service/{}".format(tenant_id, service_id)
    print "output log file : /data/docker_logs/{}/{}/stdout.log".format(tenant_id, service_id)

if __name__ == '__main__':
    main()
